from flask import Flask,render_template,request, redirect, url_for
from forms.main import indexForm
import time
import requests
import json
import os

app = Flask(__name__)

def make_post(text,name):
    url = "https://nls-gateway.cn-shanghai.aliyuncs.com/stream/v1/tts"

    body = {'appkey': '',
            'text': text,
            'token': '',
            'format': 'wav',

            'voice': '',
            'volume': '50',
            'speech_rate': '0',
            'pitch_rate': '0'
            }
    body = json.dumps(body)
    headers = {
        'Content-Type': 'application/json'
    }

    response = requests.request("POST", url, headers=headers, data=body)

    contentType = response.headers['Content-Type']
    print(contentType)
    responsebody = response.content
    if 'audio/mpeg' == contentType:
        with open('static/upload/'+name+'.wav', mode='wb') as f:
            f.write(responsebody)
        print('The POST request succeed!')
    else:
        print('The POST request failed: ' + str(responsebody))

@app.route('/',methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        name = request.form.get('name')
        text = request.form.get('text')
        # time.sleep(6)
        make_post(text,name)
        return redirect(url_for('display', name=name), code=302, Response=None)

    form = indexForm()
    return render_template('index.html', form=form)

@app.route('/display/?<string:name>',methods=['GET', 'POST'])
def display(name):

    return render_template('display.html', name=name)
